﻿using System;
using System.Web;
using System.Web.Mvc;

namespace doufu.Common
{
    public class UserAuthorize : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            bool result = false;
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            var user = httpContext.User.Identity as IUserIdentity;
            if (user == null)
            {
                return false;
            }
            var routedate = httpContext.Request.RequestContext.RouteData;
            var Controller = httpContext.Request.RequestContext.RouteData.Values["controller"].ToString();
            var action = httpContext.Request.RequestContext.RouteData.Values["action"].ToString();

            result = user.IsInRole(Controller, action);

            if (!result)
            {
                httpContext.Response.StatusCode = 403;
            }
            return result;
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
            if (filterContext.HttpContext.Response.StatusCode == 403)
            {
                filterContext.Result = new RedirectResult("/User/NoRight");
            }
        }


    }
}